// Copyright 2022 marcello<volibearw@gmail.com>. All rights reserved.

package main

import "fmt"

// generateModelFromProtoPart 生成 fromProto 部分
func generateModelFromProtoPart(param *CLIParam, tableName string, columns []Columns) string {
	var funcStr = ""
	if !param.Proto {
		// 如果没有打开生成proto, proto字段名不一致的情况出现
		// 就不生成此方法
		return funcStr
	}
	funcStr += "// FromProto 从 protobuf 定义读取\n"

	if len(columns) == 0 {
		// 表内没有字段就直接返回空函数
		funcStr += "func (" + getFirstWordToLowercase(tableName) + " *" + toCamelString(tableName) + ") FromProto("
		funcStr += getCamelStringFirstWordLowercase(tableName) + " pb." + toCamelString(tableName) + ") {\n"
		funcStr += "}\n\n"
		return funcStr
	}

	funcStr += "func (" + columns[0].TableNameFirstWordLowercase + " *" + columns[0].TableNameCame + ") FromProto("
	funcStr += columns[0].TableNameCameFirstWordLowercase + " *pb." + columns[0].TableNameCame + ") error {\n"

	var (
		parseStr  = "" // 额外处理part
		fieldLine = ""
	)

	// from proto 字段组装
	for n, column := range columns {

		if isGormDefaultModelField(column.ColumnName) {
			continue
		}

		// 特殊处理ID部分
		var (
			a = column.ColumnNameCame
			b = column.TableNameCameFirstWordLowercase + "." + column.ColumnNameCame
		)
		if param.ModelUseGorm && param.ModelIncludeGormModel {
			// gorm中id字段要使用ID
			if isGormDefaultModelIDField(column.ColumnName) {
				a = "ID"
				b = "uint(" + column.TableNameCameFirstWordLowercase + "." + column.ColumnNameCame + ")"
			}
		}

		// 处理 Datetime 转换
		if isDatetime(column) {
			var template = `	var v%d time.Time
	v%d, err := time.Parse(%s, "2006-01-02 15:04:05")
	if err != nil {
		return err
	}
`
			parseStr = fmt.Sprintf(template, n, n, column.TableNameCameFirstWordLowercase+"."+column.ColumnNameCame)
			b = fmt.Sprintf("v%d", n)
		}

		// 处理Date转换
		if isDate(column) {
			var template = `	var v%d time.Time
	v%d, err := time.Parse(%s, "2006-01-02")
	if err != nil {
		return err
	}
`
			parseStr = fmt.Sprintf(template, n, n, column.TableNameCameFirstWordLowercase+"."+column.ColumnNameCame)
			b = fmt.Sprintf("v%d", n)
		}

		fieldLine += "    " + column.TableNameFirstWordLowercase + "." + a + " = " + b + "\n"
	}

	funcStr += parseStr
	funcStr += fieldLine
	funcStr += "	return nil\n"
	funcStr += "}\n\n"
	return funcStr
}
